﻿var patientID;

$(document).ready(function () {
   
    $("#tblPatients").on("click", ".lnkCreateEncounter", function (event) {
        patientID = $(this).data("patientid");
        var patientName = $(this).closest("td").siblings("td.patientName").html();
        $("#createEncounterLabel").html("Create Encounter for " + patientName);
        $("#modCreateEncounter").modal("show");
    });

    setupPatientSearch();

    $("#tbEncounterDate").datetimepicker({ stepMinute: 10 });

    $("#btnCreateEncounter").click(function () {      
        createEncounter();
    });
});

function setupPatientSearch() {
    var thread = null;

    $('#tbPatientName').keyup(function () {
        clearTimeout(thread);
        var $this = $(this);
        thread = setTimeout(function () { findPatients($this.val()) }, 1000);
    });

}


function findPatients(searchText) {
    if (searchText == "") {
        return;
    }
    
    $("#Dashboard #tblPatientContainer .data").hide();
    $("#Dashboard #tblPatientContainer .loading").show();

    var url = 'Dashboard/FindPatients';
    
    $.ajax({
        url: url,
        data: { facilityID: facilityID, searchText: searchText },
        type: 'get',
        dataType: 'json',
        success: function (data) {
            $("#tblPatients tbody").empty();
            $(data).each(function (index) {
                var tr = "<tr><td><a class='btn btn-primary btn-mini lnkViewPatient' href='Patient?id=" + this.PatientID + "'>View Patient</a></td>";
                tr = tr + "<td><a class='btn btn-primary btn-mini lnkCreateEncounter' data-patientid='" + this.PatientID + "'>Create Appointment</a></td>";
                tr = tr + "<td class='patientName'>" + this.LName + ", " + this.FName + "</td>";
                tr = tr + "<td>" + formatJsonDate(this.DateOfBirth) + "</td></tr>";
                $("#tblPatients tbody").append(tr);
            });

            $("#Dashboard #tblPatientContainer .loading").hide();
            $("#Dashboard #tblPatientContainer .data").show();
            
        },
        error: function (data) {
            $("#Dashboard #tblPatientContainer .loading").hide();
            $("#Dashboard #tblPatientContainer .data").hide();
            alert("Dadgumitt...We had trouble finding patients for some reason.");
        }
    });

}

function createEncounter() {

    var Encounter = JSON.stringify({
        'PatientID': patientID,
        'EncounterDate': $('#tbEncounterDate').val()
    });

    var url = 'Encounter/SaveEncounter';

    $.ajax({
        url: url,
        data: { encounterJSON: Encounter },
        type: 'post',
        dataType: 'json',
        success: function (data) {
           
            alert("Encounter created");
        },
        error: function (data) {
            alert("Awww Snap...We encountered trouble saving the encounter.");
        }
    });

}